import pygame
import sys
import os
from .music_player import MusicPlayer
# 添加父目录到系统路径，确保能导入constant模块
current_dir = os.path.dirname(os.path.abspath(__file__))
parent_dir = os.path.dirname(current_dir)
sys.path.append(parent_dir)

from constant import Setting
from .button import Button

class EnterUI:
    """游戏开始界面（含背景介绍功能，支持背景图加载）"""
    
    def __init__(self):
        # 初始化pygame
        pygame.init()
        # 加载配置
        self.settings = Setting()
        # 保存项目根目录（用于拼接图片路径）
        self.root_dir = parent_dir
        
        # 屏幕初始化
        self.screen = pygame.display.set_mode(
            (self.settings.screen_width, self.settings.screen_height)
        )
        pygame.display.set_caption(self.settings.screen_title)
        
        # ---------------------- 1. 加载核心图片（新增：背景介绍界面图片）----------------------
        # 开始界面背景图
        self.start_background = self._load_background(self.settings.images_path["start_background"])
        # 背景介绍界面背景图（新增，需在constant.py配置路径）
        self.intro_background = self._load_intro_background(self.settings.images_path.get("intro_background"))
        
        # 标题图（原有逻辑保留）
        self.title_image = self._load_title_image(
            img_path=self.settings.title_images_path["start_title"],
            target_width=self.settings.btn_width + 40
        )
        
        # 创建开始界面UI元素（原有逻辑保留）
        self._create_transparent_panel()
        self._create_buttons()
        self._calculate_title_position()
        
        # 作者信息（原有逻辑保留）
        self.author_text = self.settings.font_small.render(
            "Created by Authur, Brown, Noah, Nancy", True, self.settings.color_white
        )
        self.author_rect = self.author_text.get_rect(
            bottomleft=(10, self.settings.screen_height - 10)
        )
        
        # 音乐播放器（原有逻辑保留）
        self.music_player = MusicPlayer()
        
        # ---------------------- 2. 状态控制与背景介绍初始化（新增图片相关参数）----------------------
        self.running = True
        self.start_game = False
        self.show_intro = False  # 是否显示背景介绍界面
        
        # 初始化背景介绍：文本+图片+遮罩
        self._init_intro_elements()

    def _load_intro_background(self, img_path):
        """加载背景介绍界面的背景图（适配屏幕，修复裁剪区域超出问题）"""
        # 若未配置图片路径，用深色背景 fallback
        if not img_path:
            fallback_surf = pygame.Surface((self.settings.screen_width, self.settings.screen_height))
            fallback_surf.fill((10, 10, 30))  # 深靛蓝色，适配古风/星球大战风格
            return fallback_surf

        try:
            full_path = os.path.join(self.root_dir, img_path)
            # 加载图片并缩放（保持宽高比，避免拉伸变形）
            bg = pygame.image.load(full_path).convert()

            # 计算缩放比例（确保图片覆盖屏幕，同时不拉伸）
            scale_x = self.settings.screen_width / bg.get_width()
            scale_y = self.settings.screen_height / bg.get_height()
            scale_ratio = max(scale_x, scale_y)  # 按最大比例缩放，确保覆盖屏幕
            new_width = int(bg.get_width() * scale_ratio)
            new_height = int(bg.get_height() * scale_ratio)

            # 确保缩放后的尺寸不小于屏幕尺寸（修复小图缩放问题）
            new_width = max(new_width, self.settings.screen_width)
            new_height = max(new_height, self.settings.screen_height)

            scaled_bg = pygame.transform.scale(bg, (new_width, new_height))

            # 计算裁剪区域（添加边界检查，确保不会超出图片范围）
            crop_x = max(0, (new_width - self.settings.screen_width) // 2)
            crop_y = max(0, (new_height - self.settings.screen_height) // 2)

            # 确保裁剪区域在图片范围内
            crop_width = min(self.settings.screen_width, scaled_bg.get_width() - crop_x)
            crop_height = min(self.settings.screen_height, scaled_bg.get_height() - crop_y)

            return scaled_bg.subsurface((crop_x, crop_y, crop_width, crop_height))
        except FileNotFoundError:
            print(f"【错误】未找到背景介绍图：{full_path}，使用默认背景")
            fallback_surf = pygame.Surface((self.settings.screen_width, self.settings.screen_height))
            fallback_surf.fill((10, 10, 30))
            return fallback_surf

    def _init_intro_elements(self):
        """初始化背景介绍界面元素：中英对应文本+继续按钮+半透明遮罩"""
        # 中英对应背景文本（一行中文一行英文）
        self.intro_text = [
            "天宝年间，长安作为大唐的心脏，不仅是丝路起点的繁华都会，更是诗韵流淌的文化圣殿 ——",
            "During the Tianbao era of the Tang Dynasty, Chang’an,",
            " the heart of the empire, was not only a thriving hub at the start of the Silk Road ",
            "but also a cultural sanctuary where poetic charm flowed endlessly ——",
            "朱雀大街的酒旗上题着即兴诗句，曲江池的画舫里飘着和诗的吟唱，",
            "Impromptu verses adorned the tavern flags on Zhuque Avenue, ",
            "melodic poetic responses drifted from the painted boats on Qujiang Pool,",
            "连大明宫的石阶缝隙中，都藏着文人墨客遗落的墨香。",
            "and even the cracks in the stone steps of Daming Palace held the faint ink scent of literati’s brushstrokes.",
            "然而一场突如其来的 “文脉之劫” 悄然降临：",
            "However, an unexpected 'Calamity of Literary Spirit' descended silently:",
            "一股无形的 “浊息” 顺着人们对诗歌的漠视滋生，它吞噬传世诗篇的灵气，",
            "an invisible 'Turbid Aura' grew from people’s indifference to poetry,",
            " devouring the vital essence of timeless verses.",
            "让街头巷尾的诗句褪色、石碑上的题刻模糊，",
            "Street poems faded, stone inscriptions blurred,",
            "甚至连曾让全城传唱的名篇，都渐渐被世人遗忘。",
            "and even once widely celebrated masterpieces were gradually forgotten by the people.",
            "",  # 空行分隔
            "",
            "危急时刻，沉睡在《全唐诗》典籍中的诗人英魂被唤醒。",
            "In this crisis, the souls of poets—slumbering in the ancient compilation Complete Tang Poems—awakened.",
            "他们并非手持刀剑的武将，却能以诗为刃、以字为甲 ——",
            "They were not warriors wielding swords, ",
            "yet they turned poetry into blades and words into armor ——",
            "有的凭豪迈诗句迸发破敌之力，有的借悲悯笔墨守护同伴，",
            "some unleashed destructive power with bold verses, ",
            "some protected companions with compassionate lines,",
            "有的用澄澈诗境净化浊息，有的以凌厉辞藻震慑邪祟。",
            "some purified the Turbid Aura with serene poetic realms, ",
            "and some intimidated evil with sharp, powerful phrases.",
            "玩家将化身 “守诗者”，与这些诗人魂魄结伴，",
            "As the 'Guardian of Poetry', players ally with these poet souls,",
            "从酒肆到书院，从宫殿到山野，",
            "traveling from taverns to academies, from palaces to mountains.",
            "在一场场以诗为核心的战斗中，唤醒被浊息污染的诗句，收集散落的诗魂碎片，",
            "In battles centered on poetry, players revive verses corrupted by the Turbid Aura,",
            " collect scattered fragments of poetic spirits,",
            "逐步揭开 “文脉之劫” 的根源。",
            "and gradually uncover the root of the 'Calamity of Literary Spirit'.",
            "最终，众人需在长安的文化地标之巅，以一首凝聚全城诗韵的传世之作，",
            "In the end, the group must gather at the peak of Chang’an’s cultural landmark,",
            " using a legendary poem that embodies the city’s entire poetic essence",
            "彻底驱散浊息，让长安的诗香重新弥漫在街巷与山河之间。",
            "to dispel the Turbid Aura completely, ",
            "allowing Chang’an’s poetic fragrance to once again fill its streets,",
            " lanes, mountains, and rivers."
        ]
        
        # 文本样式（调整为白色，适配深色背景图；加粗增强可读性）
        self.intro_font = pygame.font.SysFont("SimHei", 26, bold=True)
        self.intro_text_color = (255, 255, 255)  # 白色文字，清晰显示在图片上
        self.intro_line_spacing = 35  # 行间距，避免文字拥挤
        
        # ---------------------- 4. 文本滚动参数（原有逻辑保留）----------------------
        self.intro_scroll_speed = 1.2  # 放慢速度，适配图片观赏
        self.intro_text_start_y = self.settings.screen_height  # 初始位置（屏幕底部）
        
        # ---------------------- 5. 半透明遮罩（新增，关键！避免文字与图片重叠模糊）----------------------
        # 遮罩覆盖在背景图上方，降低图片亮度，让白色文字更清晰
        self.intro_mask = pygame.Surface((self.settings.screen_width, self.settings.screen_height), pygame.SRCALPHA)
        self.intro_mask.fill((0, 0, 0, 150))  # 黑色半透明（透明度150/255，可调整）
        
        # ---------------------- 6. 继续按钮（原有逻辑保留，调整位置适配图片）----------------------
        self.continue_button = Button(
            x=self.settings.screen_width - self.settings.btn_width - 30,
            y=self.settings.screen_height - self.settings.btn_height - 30,
            text="Continue",
            settings=self.settings,
            action=self._on_continue_click,
            image_path=os.path.join(self.root_dir, self.settings.button_images_path["start_ui_button"])
        )

    # ---------------------- 7. 原有方法保留（仅补充注释）----------------------
    def _load_background(self, img_path):
        """加载开始界面背景图（原有逻辑不变）"""
        try:
            full_path = os.path.join(self.root_dir, img_path)
            background = pygame.image.load(full_path).convert()
            return pygame.transform.scale(background, (self.settings.screen_width, self.settings.screen_height))
        except FileNotFoundError:
            print(f"【错误】未找到开始界面背景图：{full_path}")
            fallback_surf = pygame.Surface((self.settings.screen_width, self.settings.screen_height))
            fallback_surf.fill(self.settings.bg_path_start)
            return fallback_surf

    def _load_title_image(self, img_path, target_width):
        """加载标题图（原有逻辑不变）"""
        try:
            full_path = os.path.join(self.root_dir, img_path)
            title_img = pygame.image.load(full_path).convert_alpha()
            target_width = int(self.settings.screen_width * 0.7)
            scale_ratio = target_width / title_img.get_width()
            target_height = int(title_img.get_height() * scale_ratio)
            return pygame.transform.scale(title_img, (target_width, target_height))
        except FileNotFoundError:
            print(f"【错误】未找到标题图：{full_path}")
            target_width = int(self.settings.screen_width * 0.7)
            fallback_surf = pygame.Surface((target_width, int(target_width * 0.3)), pygame.SRCALPHA)
            fallback_surf.fill((139, 69, 19, 180))
            return fallback_surf

    def _create_transparent_panel(self):
        """创建开始界面按钮面板（原有逻辑不变）"""
        panel_width = self.settings.btn_width + 40
        panel_height = (self.settings.btn_height * 2) + (self.settings.btn_spacing * 3)
        panel_x = (self.settings.screen_width // 6) - 20
        panel_y = self.settings.screen_height // 2 - self.settings.btn_spacing
        self.panel_surface = pygame.Surface((panel_width, panel_height), pygame.SRCALPHA)
        self.panel_surface.fill((0, 0, 0, 128))
        self.panel_rect = pygame.Rect(panel_x, panel_y, panel_width, panel_height)

    def _create_buttons(self):
        """创建开始/退出按钮（原有逻辑不变）"""
        button_x = self.settings.screen_width // 6
        button_y = self.settings.screen_height // 2
        btn_img_path = os.path.join(self.root_dir, self.settings.button_images_path["start_ui_button"])
        
        self.start_button = Button(
            x=button_x, y=button_y, text="Start ", settings=self.settings,
            action=self._on_start_click, image_path=btn_img_path
        )
        
        exit_button_y = button_y + self.settings.btn_height + self.settings.btn_spacing
        self.exit_button = Button(
            x=button_x, y=exit_button_y, text="Exit", settings=self.settings,
            action=self._on_exit_click, image_path=btn_img_path
        )

    def _calculate_title_position(self):
        """计算标题图位置（原有逻辑不变）"""
        self.title_x = (self.settings.screen_width - self.title_image.get_width()) // 2
        self.title_y = int(self.settings.screen_height * 0.1)

    # ---------------------- 8. 事件处理（原有逻辑保留）----------------------
    def _on_start_click(self):
        """点击开始按钮：切换到背景介绍界面"""
        self.show_intro = True


    def _on_continue_click(self):
        """点击继续按钮：进入角色选择界面"""
        self.start_game = True
        self.running = False
        self.music_player.stop_music()

    def _on_exit_click(self):
        """点击退出按钮：关闭游戏"""
        self.running = False

    def handle_events(self):
        """事件分发：根据当前界面处理按钮事件"""
        for event in pygame.event.get():
            if event.type == pygame.QUIT:
                self.running = False
            
            if self.show_intro:
                self.continue_button.handle_event(event)  # 背景介绍界面：处理继续按钮
            else:
                self.start_button.handle_event(event)     # 开始界面：处理开始/退出按钮
                self.exit_button.handle_event(event)

    # ---------------------- 9. 绘制逻辑（核心修改：背景介绍界面加载图片）----------------------
    def draw(self):
        """根据当前界面绘制元素"""
        if self.show_intro:
            self._draw_intro_screen()  # 绘制背景介绍界面（含图片）
        else:
            self._draw_start_screen()   # 绘制开始界面（原有逻辑）
        pygame.display.flip()

    def _draw_intro_screen(self):
        """绘制背景介绍界面：图片→遮罩→滚动文字→继续按钮（层级关键！）"""
        # 1. 底层：绘制背景介绍图片
        self.screen.blit(self.intro_background, (0, 0))
        # 2. 中层：绘制半透明遮罩（降低图片亮度，让文字清晰）
        self.screen.blit(self.intro_mask, (0, 0))
        # 3. 上层：绘制滚动文字
        current_y = self.intro_text_start_y
        for line in self.intro_text:
            text_surf = self.intro_font.render(line, True, self.intro_text_color)
            # 文字水平居中（适配不同屏幕宽度）
            text_x = (self.settings.screen_width - text_surf.get_width()) // 2
            self.screen.blit(text_surf, (text_x, current_y))
            current_y += self.intro_line_spacing  # 换行
        
        # 4. 文字向上滚动（边界控制：文字完全滚出屏幕后停止）
        if current_y < -len(self.intro_text) * self.intro_line_spacing:
            self.intro_text_start_y = self.settings.screen_height  # 重置到屏幕底部
        else:
            self.intro_text_start_y -= self.intro_scroll_speed
        
        # 5. 顶层：绘制继续按钮（始终显示在右下角）
        self.continue_button.draw(self.screen)

    def _draw_start_screen(self):
        """绘制开始界面（原有逻辑保留）"""
        self.screen.blit(self.start_background, (0, 0))
        self.screen.blit(self.panel_surface, self.panel_rect)
        self.screen.blit(self.title_image, (self.title_x, self.title_y))
        self.start_button.draw(self.screen)
        self.exit_button.draw(self.screen)
        self.screen.blit(self.author_text, self.author_rect)

    # ---------------------- 10. 主循环（原有逻辑保留）----------------------
    def run(self):
        clock = pygame.time.Clock()
        while self.running:
            clock.tick(self.settings.fps)
            self.handle_events()
            self.draw()
            # 仅在开始界面播放音乐
            if not self.show_intro:
                self.music_player.play_music("start")
        # 返回是否进入游戏的状态，供main.py判断
        return self.start_game